package com.devops.admin.job;

import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author jxt
 * @Notes
 * @date 2024/1/10 9:47
 */
@Service
public class JobService {
    @Resource
    private Scheduler scheduler;

    private static final String TRIGGER_SUFFIX = "Trigger";

    public void startCronJob(String cronExpression, Class<? extends Job> jobClass, String jobName, String jobGroup,
                         JobDataMap jobDataMap) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(jobClass)
                .withIdentity(jobName, jobGroup)
                .storeDurably()
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(jobName + TRIGGER_SUFFIX, jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .usingJobData(jobDataMap)
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    public void stopJob(String jobName, String jobGroup) throws SchedulerException {
        scheduler.pauseTrigger(new TriggerKey(jobName + TRIGGER_SUFFIX, jobGroup));
        scheduler.unscheduleJob(new TriggerKey(jobName + TRIGGER_SUFFIX, jobGroup));
        scheduler.deleteJob(new JobKey(jobName, jobGroup));
    }

    public void restartJob(String cronExpression, Class<? extends Job> jobClass, String jobName, String jobGroup,
                             JobDataMap jobDataMap) throws SchedulerException {
        stopJob(jobName, jobGroup);
        startCronJob(cronExpression, jobClass, jobName, jobGroup, jobDataMap);
    }

    public void executeJobNow(Class<? extends Job> jobClass, String jobName, String jobGroup,
                              JobDataMap jobDataMap) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(jobClass)
                .withIdentity(jobName, jobGroup)
                .build();

        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity(jobName, jobGroup)
                .usingJobData(jobDataMap)
                .startNow()
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }
}
